<template>
	<xn-form-container
		:title="formData.id ? '修改关键词' : '新增关键词'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="关键词" name="keyword">
				<a-input v-model:value="formData.keyword" placeholder="请输入关键词" allow-clear/>
			</a-form-item>
			<a-form-item label="违规等级" name="level">
				<a-select
					v-model:value="formData.level"
					placeholder="违规等级"
					:options="VIOLATION_LEVEL"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="违规类型" name="type">
				<a-select
					v-model:value="formData.type"
					placeholder="违规类型"
					:options="VIOLATION_TYPE"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="质检对象" name="type">
				<a-select
					v-model:value="formData.scope"
					placeholder="请选择质检对象"
					:options="KEYWORD_SCOPE"
					allowClear
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
import {required} from '@/utils/formRules'
import keyWordApi from "@/api/qc/keyword/keyWordApi";
import tool from "@/utils/tool";
// 默认是关闭状态
const visible = ref(false)
const emit = defineEmits({successful: null})
const formRef = ref()
// 表单数据
const formData = ref({
	level: '1'
})
const VIOLATION_TYPE = tool.dictList('VIOLATION_TYPE')
const VIOLATION_LEVEL = tool.dictList('VIOLATION_LEVEL')
const KEYWORD_SCOPE = tool.dictList('KEYWORD_SCOPE')
const keywordLevelOptions = tool.dictList('KeywordLevel')

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	if (record) {
		formData.value = record
	}
}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	visible.value = false
	formData.value = {}
}

// 默认要校验的
const formRules = {
	keyword: [required('请输入关键词')],
	level: [required('请选择等级')]
}

// 验证并提交数据
const onSubmit = () => {
	formRef.value
		.validate()
		.then(() => {
			if (formData.value.id) {
				keyWordApi.editKeyword(formData.value).then(() => {
					onClose()
					emit('successful')
				})
			} else {
				keyWordApi.addKeyword(formData.value).then(() => {
					onClose()
					emit('successful')
				})
			}
		})
		.catch(() => {
		})
}

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
})
</script>
